const { TagVO: TagModel } = require("@/model/tag");

const tag = {
  async GetOption() {
    let res = await TagModel.findAll({
      attributes: ["id", "name"],
    });
    let data = res.map((item) => {
      return {
        value: item.dataValues.id,
        label: item.dataValues.name,
      };
    });

    return data;
  },
  async GetList(data) {
    let query = `
    SELECT t.id, t.name, COUNT(at.article_id) AS article_count, t.created_at, t.updated_at
    FROM tag t
    LEFT JOIN article_tag at ON t.id = at.tag_id
  `;

    // 如果有关键字，则添加过滤条件
    if (data?.keyword) {
      //筛选标签的关键字
      query += ` WHERE t.name LIKE '%${data.keyword}%'`;
    }

    // 添加分组
    query += " GROUP BY t.id ";
    query += " ORDER BY t.id DESC ";
    const [rows] = await global.mysqlPool.execute(
      `SELECT COUNT(*) as count FROM tag t`
    );
    const total = rows[0].count; //统计的数量
    if (data) {
      query += ` LIMIT ${data.page_size} OFFSET ${
        (data.page_num - 1) * data.page_size
      } `;
    }
    const [results] = await global.mysqlPool.execute(query);

    return {
      datas: results,
      total,
    };
  },
  /**
   *
   * @param {*} id 文章id
   */
  async GetTagNamesByArtId(id) {
    const query = `
      select tag.name
      from tag
      left join article_tag on tag.id = article_tag.tag_id
      where article_tag.article_id = ?
    `;
    const [result] = await global.mysqlPool.execute(query, [id]);
    //将查询的结果格式化返回
    return result.map((item) => item.name);
  },
};

module.exports = tag;
